# -*- coding: utf-8 -*-
# @file    : ws_client
# @Date    : 2020/11/19
# @Author  :
# @Version : 1.0.0
import re
import asyncio
import websockets
from websockets.client import WebSocketClientProtocol

from ._misc import load_cookie, get_abs_path
from . import exceptions
from . import constant as c
from .config import config
from .log import logger as _logger

# 用户配置
user_config = config['user']
# 正则匹配推送结果
_uid_re = re.compile(r'"\w{10,}?"')


@property
def _name(self):
    """
    WebsocketClient 自命名
    :param self:
    :return:
    """
    return "WS客户端(%s)" % id(self)


WebSocketClientProtocol.name = _name


async def client(path, queue, **context):
    """
    WebSocket 客户端
    :param path:
    :param queue: 消息队列
    :param context: 环境
    :return:
    """
    ps = context.get('_parent_socket')
    uri = "ws://" + c.POE_HOST + path
    cookie = load_cookie(get_abs_path(user_config['cookie_file']))
    if not cookie:
        raise exceptions.AppException("cookie文件未正确配置, 无法使用实时搜索")
    headers = {
        'Host': c.POE_HOST,
        'Origin': c.POE_REMOTE,
        'Cookie': cookie,
    }

    async with websockets.connect(uri=uri, extra_headers=headers) as websocket:
        _logger.info("%s: 启动", websocket.name)
        while not (websocket.closed or ps.closed if ps else False):
            response = await websocket.recv()
            if response == '{"auth":true}':
                continue
            count = len(_uid_re.findall(response))
            _logger.info("%s: 收到推送, %s条", websocket.name, count)
            await queue.put(response)
        _logger.info("%s: 关闭", websocket.name)


def test():
    q = asyncio.Queue()
    test_path = "/api/trade/live/S13%E8%B5%9B%E5%AD%A3/1JZrIl"
    asyncio.get_event_loop().run_until_complete(client(test_path, q))


def start(path, queue):
    asyncio.get_event_loop().run_until_complete(client(path, queue))
